package com.example.qrcodecamera;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.util.List;

public class MaterialmysqlViewActivity extends AppCompatActivity {
    private static final int PAGE_SIZE = 10;
    private int currentPage = 1;
    private int totalRecords = 0;

    private TableLayout tableLayout;
    private Button btnPrev, btnNext,btnback;
    private TextView tvPageInfo;
    private MaterialDatabaseHelper dbHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewmysql_data);

        // 初始化视图
        tableLayout = findViewById(R.id.table_data);
        btnPrev = findViewById(R.id.btn_prev);
        btnNext = findViewById(R.id.btn_next);
        tvPageInfo = findViewById(R.id.tv_page_info);
        dbHelper = new MaterialDatabaseHelper(this);
        btnback = findViewById(R.id.btn_back);





        // 初始化数据
        totalRecords = dbHelper.getmysqlTotalCount();
        btnPrev.setOnClickListener(v -> loadPage(currentPage - 1));
        btnNext.setOnClickListener(v -> loadPage(currentPage + 1));
        btnback.setOnClickListener(v->finish());
        loadPage(1);
    }

    private void loadPage(int page) {
        if (page < 1 || page > getTotalPages()) return;
        currentPage = page;
        tableLayout.removeAllViews();

        List<MaterialInfo> data = dbHelper.getPagedData(page, PAGE_SIZE);
        for (MaterialInfo item : data) {
            TableRow row = new TableRow(this);
            addCell(row, item.getStorageTime());
            addCell(row, item.getMaterialId());
            addCell(row, item.getGrossWeight());
            addCell(row, item.getNetWeight());
            tableLayout.addView(row);
        }

        updatePaginationUI();
    }

    private void addCell(TableRow row, String text) {
        TextView tv = new TextView(this);
        tv.setText(text);
        tv.setPadding(8, 12, 8, 12);
        tv.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 1f));
        row.addView(tv);
    }

    private int getTotalPages() {
        return (int) Math.ceil((double) totalRecords / PAGE_SIZE);
    }

    private void updatePaginationUI() {
        tvPageInfo.setText(String.format("第%d页/共%d页", currentPage, getTotalPages()));
        btnPrev.setEnabled(currentPage > 1);
        btnNext.setEnabled(currentPage < getTotalPages());
    }
}